<template>
  <gc-dialog
    title="资源权限分配"
    :dialog-visible="true"
    @cancel="handleCancle"
    @ok="handleConfirm"
    width="660"
  >
    <el-form
      ref="formRef"
      label-position="top"
      :model="form"
    >
      <el-form-item label="权限分配" prop="roleIds">
        <el-tree
          ref="treeRef"
          style="width: 100%"
          default-expand-all
          :data="resourceTree"
          :props="{ label: 'name', class: customNodeClass as any }"
          show-checkbox
          node-key="id"
        />
      </el-form-item>
    </el-form>
  </gc-dialog>
</template>

<script setup lang="ts" name="OperateRoleModal">
import { ref, reactive } from 'vue'
import { ElMessage, ElTree, type FormInstance } from 'element-plus'
import { apiGetRolePermissions, apiGetResourceTreeList, apiRoleAssignPermission } from '@/http/service'
import { type ResourceTree } from '@/http/type'

const props = defineProps({
  roleId: Number
})
const emit = defineEmits(['close-modal'])
const treeRef = ref<null | InstanceType<typeof ElTree>>(null)
const formRef = ref<null | FormInstance>(null)
const form = reactive({
  roleIds: []
})
const resourceTree = ref<Array<ResourceTree>>([])

function customNodeClass (data: ResourceTree) {
  if (data.children?.length) {
    if (data.children[0].type === 'btn') {
      return 'is-penultimate'
    }
  }
  return null
}

/**
 * 查询该角色下已存在的资源权限列表
 */
async function findRoleHasPermissions () {
  try {
    const data = await apiGetRolePermissions<Array<number>>(props.roleId as number)
    return data
  } catch (error) {
    return []
  }
}

/**
 * 权限资源树列表获取
 */
async function findResourceTreeList () {
  const data = await apiGetResourceTreeList<Array<ResourceTree>>({})
  resourceTree.value = data
  const hasPermissionIds = await findRoleHasPermissions()
  if (treeRef.value) {
    treeRef.value.setCheckedKeys(hasPermissionIds, false)
  }
}
findResourceTreeList()

async function handleConfirm () {
  const valid = await formRef.value?.validate()
  if (valid) {
    const selectNodes = treeRef.value?.getCheckedNodes(false, true) as Array<ResourceTree>
    await apiRoleAssignPermission({
      roleId: props.roleId,
      permissionIds: selectNodes.map(o => o.id)
    })
    ElMessage.success('资源分配成功')
    emit('close-modal')
  }
}

function handleCancle () {
  emit('close-modal')
}
</script>

<style scoped lang="scss">
:deep(.is-penultimate) {
  .el-tree-node__children {
    padding-left: 54px;
    height: 26px;
    .el-tree-node {
      display: inline-block;
      .el-tree-node__content {
        padding-left: 12px !important;
        padding-right: 12px;
        .el-tree-node__expand-icon.is-leaf {
          display: none;
        }
      }
    }
  }
}
</style>
